import axios from "axios";
import router from "../router/index.js";
import {API_BASE_URL} from "../untils/base_url.js";
import NProgress from "nprogress"; // 引入NProgress
import "nprogress/nprogress.css"; // 引入NProgress的CSS样式
import {ElMessage} from 'element-plus'
//关闭转圈
NProgress.configure({
    showSpinner: false
})

/**
 * axios基础配置
 * @type {axios.AxiosInstance}
 */
const serverAxios = axios.create({
    baseURL: API_BASE_URL,
    timeout: 30000,
});

/**
 * 请求拦截器
 */
serverAxios.interceptors.request.use(
    (config) => {
        if (localStorage.getItem("token")) {
            config.headers.Authorization = localStorage.getItem("token")
        }
        return config;
    },
    (error) => {
        return Promise.reject(error);
    }
);

/**
 * 响应拦截器
 */
serverAxios.interceptors.response.use(
    (response) => {
        // 在请求结束时隐藏进度条
        NProgress.done();
        //管理员身份失效
        return response;
    },
    (error) => {
        // 在请求结束时隐藏进度条
        NProgress.done();
        if (error.response.status === 401) {
            localStorage.clear()
            router.push('/login').catch(() => {
            })
            ElMessage.error(error.response.data.message);
        }else {
            ElMessage.error(error);
        }

        return Promise.reject(error);
    }
);

export default serverAxios;
